package com.tanhua.server.interceptor;

import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 该拦截器提供的功能是对token进行拦截校验
 */
@Component
public class TokenCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println(request.getRequestURI());
        System.out.println(request.getRequestURL());
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //1.如果使用了注解NoAuthorization就不进行token校验了
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }
        //2.获取token,进行token校验
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)) {
            User tokenCheck = userService.getTokenCheck(token);
            if (tokenCheck != null) {
                UserThreadLocal.set(tokenCheck);
                return true;
            }
        }
        response.setStatus(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }


}
